// app.ts
import { getCurrentConfig, buildApiUrl, getCurrentEnv } from './utils/config';
import { ExamUtils } from './utils/examUtils';

// 扩展全局类型声明
declare global {
  interface IAppOption {
    globalConfig: {
      config: ReturnType<typeof getCurrentConfig>;
    };
    buildApiUrl: typeof buildApiUrl;
    isDevEnv: () => boolean;
    globalData: {
      examUtils: typeof ExamUtils;
    };
  }
}


App<IAppOption>({
  globalConfig: {
    config: getCurrentConfig()
  },
  buildApiUrl,
  isDevEnv() {
    return this.globalConfig.config.debug;
  },
  globalData: {
    examUtils: ExamUtils
  },

  onLaunch() {
    // 打印当前环境信息

    console.log('当前环境', getCurrentEnv());
    console.log('当前环境配置:', this.globalConfig.config);
    // 开发环境下启用调试工具
    if (this.isDevEnv()) {
      wx.enableAlertBeforeUnload({ message: '确定要离开小程序吗？' });
      wx.setEnableDebug({ enableDebug: true });
    }

    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    this.login();
  },

  login: function () {
    wx.login({
      success: (res) => {
        if (res.code) {
          wx.request({
            url: buildApiUrl('/api/auth/wechat'),
            method: 'POST',
            data: {
              code: res.code
            },
            success: (res) => {
              if (res.statusCode === 200) {
                // 存储token和openid
                wx.setStorageSync('token', res.data.token);
                wx.setStorageSync('openid', res.data.openid);
                console.log('登录成功 openid:' + res.data.openid + ',token:' + res.data.token)
              } else {
                console.log('登录失败');
              }
            }
          });
        } else {
          console.log('登录失败！' + res.errMsg);
        }
      }
    });
  }
})